#include <avr/io.h>
#include <util/delay.h>
#include <avr/pgmspace.h>
#include <stdint.h>
#include <stdlib.h>


void init_uart(uint8_t test){
	PORTC.OUT |= (1<<PIN7);
	PORTC.DIR |= (1<<PIN7);
	
	USARTC1.CTRLC = USART_CHSIZE_8BIT_gc;
	USARTC1.BAUDCTRLA = 33; //9600 Baud @ 2 MHz => 801
	USARTC1.BAUDCTRLB = 0xB3; //BSEL = 801 => 0x321 

	USARTC1.CTRLB |= (1<<USART_TXEN_bp) | (1<<USART_RXEN_bp);

}


void uart_putc(unsigned char c){

	while (!(USARTC1_STATUS & (1<<USART_DREIF_bp)));
	if (c == '\n'){
		USARTC1_DATA = '\r';
	 	while (!(USARTC1_STATUS & (1<<USART_DREIF_bp))); 	

	}
	USARTC1_DATA = c;

}

void uart_puts (char *s)
{
	while (*s){  
		uart_putc(*s);
		s++;
	}
}


void uart_puthex(unsigned int value){
	char i;
	char buf[9];
	static const char	hex[] = "0123456789ABCDEF";

	for (i = 0; i < 8; i++) {
		buf[7-i] = hex[value & 15];
		value >>= 4;
	}
	buf[8] = '\0';
	uart_puts(buf);
}

void uart_puthexbyte(uint8_t value){

	char buf[3];
	static const char	hex[] = "0123456789ABCDEF";

	buf[1] = hex[value & 0x0F];
	buf[0] = hex[(value >> 4) &0xF];
	
	buf[2] = '\0';
	uart_puts(buf);
}

void uart_putint(unsigned int value){
	char temp[7];
	itoa(value,temp,10);
	uart_puts(temp);
}


unsigned char uart_getc(){
	while(!(USARTC1_STATUS & (1<<USART_RXCIF_bp)));
	return USARTC1_DATA;
}


 
void uart_gets(char *buffer){
	do{
		*buffer = uart_getc();
		uart_putc(*buffer);
	}while(*buffer++ != '\r');
}
